package com.summer.common.utils;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Component
public class EmailUtils {

    @Resource
    private JavaMailSender emailSender;

    public void sendSimpleMessage(String to, String subject, String text) {
        MimeMessage message = emailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        try {
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        emailSender.send(message);
    }

    public void sendMessageWithMultipleAttachments(String to, String subject, String text, List<String> attachmentPaths) {
        MimeMessage message = emailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, true);

            for (String attachmentPath : attachmentPaths) {
                File file = new File(attachmentPath);
                if (file.exists()) {
                    InputStream inputStream = new FileInputStream(file);
                    byte[] fileBytes = IOUtils.toByteArray(inputStream);
                    inputStream.close();

                    helper.addAttachment(file.getName(), new ByteArrayResource(fileBytes));
                }
            }
        } catch (MessagingException | IOException e) {
            e.printStackTrace();
        }

        emailSender.send(message);
    }
}
